package com.shenmazg6.sentinel.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;

/**
 * @author 军哥
 * @version 1.0
 * @description: HelloSentinelController
 * @date 2022/12/28 11:48
 */

@RestController
@Slf4j
@RequestMapping(value = "/hello")
public class HelloSentinelController {

    /**
     * 定义限流规则
     * PostConstruct 构造方法执行完后执行方法定义和加载限流规则
     */
//    @PostConstruct
//    public void initFlowRules() {
//
//        log.info("初始化流控规则...");
//
//        // 定义限流规则集合
//        ArrayList<FlowRule> flowRuleArrayList = new ArrayList<FlowRule>();
//
//        // 定义限流规则
//        FlowRule flowRule = new FlowRule();
//        flowRule.setResource("helloWorld1");
//        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
//        flowRule.setCount(1);
//
//        // 加载规则集合
//        flowRuleArrayList.add(flowRule);
//
//        FlowRuleManager.loadRules(flowRuleArrayList);
//    }

    /**
     * 测试熔断
     * @return
     */

    @GetMapping(value = "/helloWorld1")
    public String helloWorld1() {
        try(Entry entry = SphU.entry("helloWorld1")) {
            // 正常流程
            long millis = System.currentTimeMillis();
            log.info("helloWorld1="+millis);

            return "hello,world1:" + millis;
        }
        catch (Exception exception) {
            // 系统降级
            log.error("系统繁忙，请稍后再试！");
            return "系统繁忙，请稍后再试！";
        }
    }

}
